package NG::Gen::Task::Search;
use strict;
use warnings;
use utf8;

use NG::Sys::App;
use NG::Gen::Battle::Side;
use NG::Gen::Battle::Battle;

use NG::Sys::Data;
use NG::Sys::Datetime;
our @ISA = qw(NG::Gen::Task::Task);

sub mutate {
	my $self = shift;
	if(my $target = app->search->search($self->{user})){
		$self->{param}{title} = $target->title;
		$target->lock_free;
		return 0;
	}else{
		$self->{param}{title} = undef;
		return "Никого не нашли";
	}
}
sub make_context {
	my $self = shift;
	my $ref = app->reference("units");
	my @ul;
	for(@{$self->{leader}->units->list}){
		if($_->{count}){
			push @ul, {
				type => copy_hash($ref->get_by_key($_->{proto_id}),"entry","type","title","img"),
				count => $_->{count},
			};
		}
	}
	return {
		units => \@ul,
	};
}

sub before_done {
	my $self = shift;
	
	my $user;
	my $leader;
	if(my $title = $self->param->{title}){
		$user = app->users->get_by_login($title);
	}
	if($user){
		$user->lock_get;
		$leader = $user->find_defender_leader;
	}else{
		$self->{result} = "Противник не найден.";
		return 0;
	}
	unless($leader){
		$self->{result} = "База без защиты. Победа";
		$user->lock_free;
		return 0;
	}

	my $s1 = NG::Gen::Battle::Side->new_from_user($self->{user},$self->{leader});
	my $s2 = NG::Gen::Battle::Side->new_from_user($user,$leader);

	my @log;
	app->mark_time("battle");
	my $res = calc_battle($s1,$s2,\@log);
	my $spend = app->mark_time("battle");
	push @log,["stat",$spend,1/$spend,scalar @log,@log/$spend];
	my $text1;
	my $text2;
	if($res == 1){
		$text2 = "Поражение";
		$text1 = "Победа";
	}
	elsif($res == 2){
		$text1 = "Поражение";
		$text2 = "Победа";
	}
	else{
		$text2 = $text1 = "Ничья";
	}
	my $row = {
		title => "$s1->{title} vs. $s2->{title}",
		date => unixtime2timestamp(),
		result => $res,
		log => \@log,
		side => $self->{task}->context,
	};
	my $log_id = app->store("battle_log")->insert($row);

	delete @{$row}{("log","side")};
	$row->{log_id} = $log_id;
	$row->{enemy_id} = 0;

	my $entry = $self->{user}->lbattle->insert($row);
	$self->{add} = {
				log_id => $log_id,
				entry => $entry,
			};

	$user->lbattle->insert($row);
	$user->levent->insert({
		title => "Нападение",
		date => unixtime2timestamp(),
		message => $self->{user}->title." напал. ".$text2,
		});
	if($user->online){
		$user->chat_command("mc.game.refresh" => {
			message => "Нападение: ".$self->{user}->title,
			profile => 1,
			battle => 1,
			event => 1,
		});
	}
	$user->lock_free;

	$self->{result} = $text1;

	return 0;
}
sub after_done {
	my $self = shift;
	if($self->{user}->online){
		$self->{user}->chat_command("mc.game.refresh" => {
			message => "Завершено: ".$self->{proto}{title},
			leader => $self->{leader}->entry,
			task => 1,
			profile => 1,
			battle => 1,
		});
	}
	return 0;
}


1;
